package jnpf.zcasset.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcCustomerEntity;
import jnpf.zcasset.mapper.ZcCustomerMapper;
import jnpf.zcasset.model.zccustomer.ZcCustomerForm;
import jnpf.zcasset.model.zccustomer.ZcCustomerPagination;
import jnpf.zcasset.service.ZcCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户信息
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期：
 */
@Service
public class ZcCustomerServiceImpl extends ServiceImpl<ZcCustomerMapper, ZcCustomerEntity> implements ZcCustomerService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Override
    public List<ZcCustomerEntity> getList(ZcCustomerPagination zcCustomerPagination) {
        return getTypeList(zcCustomerPagination, zcCustomerPagination.getDataType());
    }

    @Override
    public List<ZcCustomerEntity> getTypeList(ZcCustomerPagination zcCustomerPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcCustomerNum = 0;
        QueryWrapper<ZcCustomerEntity> zcCustomerQueryWrapper = new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcCustomerPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcCustomerPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcCustomerNum1 = 0;
            QueryWrapper<ZcCustomerEntity> zcCustomerSuperWrapper = new QueryWrapper<>();
            zcCustomerNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcCustomerSuperWrapper, superQueryList, matchLogic, "zcCustomer")
                    , new ZcCustomerEntity(), zcCustomerNum1);
            if (zcCustomerNum1 > 0) {
                List<String> zcCustomerList = this.list(zcCustomerSuperWrapper).stream().map(ZcCustomerEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcCustomerList);
                intersectionSuperList.add(zcCustomerList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcCustomerObj = authorizeService.getCondition(new AuthorizeConditionModel(zcCustomerQueryWrapper, zcCustomerPagination.getMenuId(), "zc_customer"));
                if (ObjectUtil.isEmpty(zcCustomerObj)) {
                    return new ArrayList<>();
                } else {
                    zcCustomerQueryWrapper = (QueryWrapper<ZcCustomerEntity>) zcCustomerObj;
                    zcCustomerNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcCustomerObj = authorizeService.getCondition(new AuthorizeConditionModel(zcCustomerQueryWrapper, zcCustomerPagination.getMenuId(), "zcCustomer"));
                if (ObjectUtil.isEmpty(zcCustomerObj)) {
                    return new ArrayList<>();
                } else {
                    zcCustomerQueryWrapper = (QueryWrapper<ZcCustomerEntity>) zcCustomerObj;
                    zcCustomerNum++;
                }
            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcCustomerPagination.getCustomerName())) {
                zcCustomerNum++;
                zcCustomerQueryWrapper.lambda().like(ZcCustomerEntity::getCustomerName, zcCustomerPagination.getCustomerName());
            }

            if (ObjectUtil.isNotEmpty(zcCustomerPagination.getProject())) {
                zcCustomerNum++;
                zcCustomerQueryWrapper.lambda().like(ZcCustomerEntity::getProject, zcCustomerPagination.getProject());
            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcCustomerQueryWrapper.lambda().in(ZcCustomerEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcCustomerQueryWrapper.lambda().and(t -> t.in(ZcCustomerEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcCustomerPagination.getSidx())) {
            zcCustomerQueryWrapper.lambda().orderByDesc(ZcCustomerEntity::getId);
        } else {
            try {
                String sidx = zcCustomerPagination.getSidx();
                ZcCustomerEntity zcCustomerEntity = new ZcCustomerEntity();
                Field declaredField = zcCustomerEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcCustomerQueryWrapper = "asc".equals(zcCustomerPagination.getSort().toLowerCase()) ? zcCustomerQueryWrapper.orderByAsc(value) : zcCustomerQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcCustomerEntity> page = new Page<>(zcCustomerPagination.getCurrentPage(), zcCustomerPagination.getPageSize());
                IPage<ZcCustomerEntity> userIPage = this.page(page, zcCustomerQueryWrapper);
                return zcCustomerPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcCustomerEntity> list = new ArrayList();
                return zcCustomerPagination.setData(list, list.size());
            }
        } else {
            return this.list(zcCustomerQueryWrapper);
        }
    }

    @Override
    public ZcCustomerEntity getInfo(String id) {
        QueryWrapper<ZcCustomerEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcCustomerEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcCustomerEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcCustomerEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcCustomerEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcCustomerForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getCustomerName())) {
            QueryWrapper<ZcCustomerEntity> customerNameWrapper = new QueryWrapper<>();
            customerNameWrapper.lambda().eq(ZcCustomerEntity::getCustomerName, form.getCustomerName());
            if (isUp) {
                customerNameWrapper.lambda().ne(ZcCustomerEntity::getId, id);
            }
            if ((int) this.count(customerNameWrapper) > 0) {
                total++;
            }
        }
        if (total > 0) {
            return true;
        }
        return false;
    }
}
